<template>
  <div>
    <div class="head-container">
      <el-form :inline="true" :model="dataForm">
        <el-input
          v-model="dataForm.taskName"
          clearable
          size="small"
          placeholder="请输入Bean名称"
          style="width: 200px"
          class="filter-item"
        />
        <el-date-picker
          v-model="dataForm.createTime"
          type="daterange"
          size="small"
          unlink-panels
          range-separator=":"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          class="date-item"
        >
        </el-date-picker>
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          @click="getDataList()"
          >搜索</el-button
        >
        <el-button
          v-if="isAuth('tools:quartz:save')"
          class="filter-item"
          size="mini"
          type="success"
          @click="addOrUpdateHandle()"
          >新增</el-button
        >
        <el-button
          v-if="isAuth('tools:quartz:export')"
          class="filter-item"
          size="mini"
          type="warning"
          :disabled="!dataList.length"
          @click="doExport()"
          >导出</el-button
        >
        <el-button
          v-if="isAuth('tools:quartz:delete')"
          class="filter-item"
          type="danger"
          size="mini"
          :disabled="dataListSelections.length <= 0"
          @click="deleteHandle()"
          >批量删除</el-button
        >
        <el-button class="filter-item" type="info" size="mini" @click="logHandle()"
          >日志
        </el-button>
      </el-form>
    </div>
    <el-table :data="dataList" style="width: 100%" v-loading="dataListLoading" @selection-change="selectionChangeHandle">
      <el-table-column
        header-align="center"
        align="center"
        type="selection"
        width="50"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="jobId"
        label="任务ID"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="beanName"
        label="Bean名称"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="params"
        label="参数"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="cronExpression"
        label="cron表达式"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="status"
        width="90px"
        label="状态"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == 1 ? 'warning' : 'success'">
            {{scope.row.status == 1 ? "暂停" : "正常"}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        prop="remark"
        width="150px"
        label="描述"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="createTime"
        width="180px"
        label="创建日期"
      >
      </el-table-column>
      <el-table-column label="操作" width="170px" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="isAuth('tools:quartz:update')"
            size="mini"
            style="margin-right: 3px"
            type="text"
            @click="addOrUpdateHandle(scope.row.jobId)"
            >编辑</el-button
          >
          <el-button
            v-if="isAuth('tools:quartz:run')"
            style="margin-left: -2px"
            type="text"
            size="mini"
            @click="execute(scope.row.jobId)"
            >执行</el-button
          >
          <el-button
            v-if="isAuth('tools:quartz:pause') || isAuth('tools:quartz:resume')"
            style="margin-left: 3px"
            type="text"
            size="mini"
            @click="updateStatus(scope.row.jobId,scope.row.status == 1 ? '恢复' : '暂停')"
          >
            {{ scope.row.status == 1 ? "恢复" : "暂停" }}
          </el-button>
          <el-button v-if="isAuth('tools:quartz:delete')" type="text" size="small" @click="deleteHandle(scope.row.jobId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></add-or-update>

    <!-- 弹窗, 日志列表 -->
    <log v-if="logVisible" ref="log"></log>
  </div>
</template>

<script>
import AddOrUpdate from './quartz-add-or-update'
import Log from './quartz-log'
import { parseTime, downloadFile } from '@/utils'
export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const start = new Date();
            const end = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      dataForm: {
        taskName: '',
        createTime: []
      },
      dataList: [],
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      logVisible: false,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
    }
  },
  components: {
    AddOrUpdate,
    Log
  },
  activated() {
    this.getDataList();
  },
  methods: {
    getDataList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/tools/quartz-job/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'taskName': this.dataForm.taskName,
          'createTime': this.dataForm.createTime ? parseTime(this.dataForm.createTime[0], '{y}-{m}-{d}') : null,
          'endTime': this.dataForm.createTime ? parseTime(this.dataForm.createTime[1], '{y}-{m}-{d}') : null
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          //console.log(data.page)
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
    //导出
    doExport() {
      this.$http({
        url: this.$http.adornUrl('/tools/quartz-job/download'),
        method: 'get',
        params: this.$http.adornParams({
          'taskName': this.dataForm.taskName,
          'createTime': this.dataForm.createTime ? parseTime(this.dataForm.createTime[0], '{y}-{m}-{d}') : null,
          'endTime': this.dataForm.createTime ? parseTime(this.dataForm.createTime[1], '{y}-{m}-{d}') : null
        }),
        responseType: 'blob'
      }).then(function (res) {
        //console.log(res);
        downloadFile(res.data, '定时任务数据', 'xlsx')
      })
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    //执行定时任务
    execute(id) {
      this.$confirm(`确定进行执行此定时任务?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/tools/quartz-job/run'),
          method: 'post',
          data: this.$http.adornData(id, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => { })
    },
    //恢复 / 暂停
    updateStatus(id, status) {
      if (status === '恢复') {
        this.resumeHandle(id)
      }else{
        this.pauseHandle(id)
      }
    },
    //恢复
    resumeHandle(id){
      this.$confirm(`确定恢复此定时任务?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/tools/quartz-job/resume'),
            method: 'post',
            data: this.$http.adornData(id, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {})
    },
    //暂停
    pauseHandle(id){
      this.$confirm(`确定暂停此定时任务?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/tools/quartz-job/pause'),
            method: 'post',
            data: this.$http.adornData(id, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {})
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    //删除
    deleteHandle(id){
      var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.jobId
      })
      this.$confirm(`确定进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/tools/quartz-job/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {})
    },
    // 日志列表
    logHandle () {
      this.logVisible = true
      this.$nextTick(() => {
        this.$refs.log.init()
      })
    }
  }
}
</script>

<style scoped>
.el-dialog__body {
  padding: 0 20px 10px 20px !important;
}
</style>
